﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace RIFF
{
    public struct Chunk
    {
        public byte[] Data;
        public Int32 Tag;

        public static Chunk Read(Stream source)
        {
            BinaryReader reader = new BinaryReader(source);
            Int32 length;
            Chunk result = new Chunk();

            result.Tag = reader.ReadInt32();
            length = reader.ReadInt32();
            result.Data = new byte[length];
            source.Read(result.Data, 0, length);

            return result;
        }

        public void Write(Stream target)
        {
            BinaryWriter writer = new BinaryWriter(target);
            Int32 length;

            if (Data != null)
            {
                length = Data.Length;
            }
            else
            {
                length = 0;
            }

            writer.Write(Tag);
            writer.Write(length);

            if (length > 0)
            {
                writer.Write(Data);
            }
        }
    }
}
